﻿using Dtmcli;
using Microsoft.AspNetCore.Mvc;
using MQCommon.SagaModel;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SagaAggregateServices.Controllers
{
    [Route("/api")]
    [ApiController]
    public class TccCtreatController : ControllerBase
    {

        private readonly TccGlobalTransaction _globalTransaction;


        public TccCtreatController( TccGlobalTransaction transaction)
        {

            _globalTransaction = transaction;
        }
        /// <summary>
        /// TCC 成功提交
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("tcc")]
        public async Task<IActionResult> Tcc()
        {
            try
            {
                OrderModel body = new OrderModel();
                body.Id = 1;
                body.UserId = 1;
                body.BusinessID = 1;
                body.Money = 1;
                body.UserName = "tcc22";
                body.BusinessName = "tcc33";
                CancellationToken cancellationToken = new CancellationToken();
                await _globalTransaction.Excecute(async (tcc) =>
                {
                    // 用户1 转出1元 第一个参数是try检测及冻结阶段，第二个是提交，第三个是回滚
                    var res1 = await tcc.CallBranch(body,
                        "http://175.178.81.27:5010/api/TccUserTry",
                         "http://175.178.81.27:5010/api/TccUserConfirm",
                         "http://175.178.81.27:5010/api/TccUserCancel", cancellationToken);

                    // 用户2 转入1元
                    var res2 = await tcc.CallBranch(body,
                        "http://119.29.92.184:5010/api/TccBusinessTry",
                         "http://119.29.92.184:5010/api/TccBusinessConfirm",
                         "http://119.29.92.184:5010/api/TccBusinessCancel", cancellationToken);

                }, cancellationToken);

                return Ok(TransResponse.BuildSucceedResponse());
            }
            catch (Exception ex)
            {
                return Ok(TransResponse.BuildFailureResponse());
            }
        }


    }
}
